package org.v2ray.rocket.proxy.support.network

import okhttp3.Response
import org.v2ray.rocket.proxy.support.network.model.BaseResponse
import rxhttp.wrapper.annotation.Parser
import rxhttp.wrapper.exception.ParseException
import rxhttp.wrapper.parse.TypeParser
import rxhttp.wrapper.utils.Converter
import java.io.IOException
import java.lang.reflect.Type

@Parser(name = "Response")
public class ResponseParser<T> : TypeParser<T> {

    //该构造方法是必须的
    protected constructor() : super()

    //如果依赖了RxJava，该构造方法也是必须的
    public constructor(type: Type) : super(type)

    @Throws(IOException::class)
    override fun onParse(response: Response): T {
        //将okhttp3.Response转换为自定义的Response对象
        val data = Converter.convertTo(
            response,
            BaseResponse::class.java, *types
        ) as BaseResponse<T> //这里的types就是自定义Response<T>里面的泛型类型
        val t = data.data //获取data字段
        if (data.isSuccess() && t != null) {
            return t
        } else {
            //抛出异常
            throw ParseException(data.code.toString(), data.msg, response)
        }
    }
}